package com.zxgj.datadirect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxgj.datadirect.domain.DataDirectResource;
import com.zxgj.datadirect.entity.NationalResourceData;
import com.zxgj.datadirect.entity.req.NationalResourceReq;
import com.zxgj.datadirect.mapper.DataDirectResourceMapper;
import com.zxgj.datadirect.service.DataDirectResourceService;
import com.zxgj.common.exception.ServiceException;
import com.zxgj.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 数据资源服务实现类
 * 对应《数据直达基层相关接口开发规范》中的数据资源管理功能
 */
@Slf4j
@Service
public class DataDirectResourceServiceImpl extends ServiceImpl<DataDirectResourceMapper, DataDirectResource>
        implements DataDirectResourceService {

    @Autowired
    private DataDirectResourceMapper dataDirectResourceMapper;

    /**
     * 查询所有数据资源列表
     * @return 数据资源列表
     */
    @Override
    public List<DataDirectResource> listResource() {
        return this.list();
    }

    /**
     * 根据ID查询数据资源详情
     * @param id 资源ID
     * @return 数据资源对象
     */
    @Override
    public DataDirectResource getResourceById(Long id) {
        if (id == null) {
            return null;
        }
        return this.getById(id);
    }

    /**
     * 保存数据资源
     * @param resource 数据资源对象
     * @return 是否保存成功
     */
    @Override
    public boolean saveResource(DataDirectResource resource) {
        if (resource == null) {
            return false;
        }
        return this.save(resource);
    }

    /**
     * 更新数据资源
     * @param resource 数据资源对象
     * @return 是否更新成功
     */
    @Override
    public boolean updateResource(DataDirectResource resource) {
        if (resource == null || resource.getId() == null) {
            return false;
        }
        return this.updateById(resource);
    }

    /**
     * 删除数据资源
     * @param id 资源ID
     * @return 是否删除成功
     */
    @Override
    public boolean deleteResource(Long id) {
        if (id == null) {
            return false;
        }
        return this.removeById(id);
    }

    /**
     * 同步国家资源数据到本地
     * @param resourceReq 国家资源请求参数
     * @return 同步成功的记录数
     */
    @Override
    @Transactional
    public int syncResourceFromNational(NationalResourceReq resourceReq) {
        if (resourceReq == null) {
            return 0;
        }
        
        int syncCount = 0;
        try {
            // 1. 参数校验
            if (StringUtils.isEmpty(resourceReq.getResourceType())) {
                throw new ServiceException("资源类型不能为空");
            }
            
            // 2. 调用外部API获取国家资源数据
            // 这里应该调用实际的Feign客户端或HTTP客户端
            List<NationalResourceData> nationalResources = getNationalResources(resourceReq);
            
            if (nationalResources == null || nationalResources.isEmpty()) {
                log.warn("未获取到国家资源数据");
                return 0;
            }
            
            // 3. 数据转换和验证
            List<DataDirectResource> localResources = new ArrayList<>();
            for (NationalResourceData nationalData : nationalResources) {
                DataDirectResource localResource = convertToLocalResource(nationalData);
                if (localResource != null) {
                    localResources.add(localResource);
                }
            }
            
            // 4. 批量保存或更新
            if (!localResources.isEmpty()) {
                for (DataDirectResource resource : localResources) {
                    // 检查是否已存在相同资源
                    LambdaQueryWrapper<DataDirectResource> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(DataDirectResource::getResourceCode, resource.getResourceCode());
                    
                    DataDirectResource existingResource = this.getOne(wrapper);
                    if (existingResource != null) {
                        // 更新现有资源
                        resource.setId(existingResource.getId());
                        resource.setUpdateTime(new Date());
                        if (this.updateById(resource)) {
                            syncCount++;
                        }
                    } else {
                        // 新增资源
                        resource.setCreateTime(new Date());
                        resource.setUpdateTime(new Date());
                        if (this.save(resource)) {
                            syncCount++;
                        }
                    }
                }
            }
            
            log.info("同步国家资源数据完成，成功同步 {} 条记录", syncCount);
            
        } catch (Exception e) {
            log.error("同步国家资源数据失败", e);
            throw new ServiceException("同步国家资源数据失败: " + e.getMessage());
        }
        
        return syncCount;
    }
    
    /**
     * 获取国家资源数据
     */
    private List<NationalResourceData> getNationalResources(NationalResourceReq resourceReq) {
        try {
            // 实际项目中应该调用 Feign 客户端或 HTTP 客户端获取数据
            // 示例：return nationalDataDirectFeign.getResources(resourceReq);
            
            // 模拟数据获取逻辑
            log.info("获取国家资源数据，资源类型: {}", resourceReq.getResourceType());
            
            // 这里应该根据实际业务需求实现具体的API调用
            // 暂时返回空列表，实际项目中需要替换为真实的API调用
            return new ArrayList<>();
            
        } catch (Exception e) {
            log.error("获取国家资源数据失败，资源类型: {}, 错误信息: {}", 
                     resourceReq.getResourceType(), e.getMessage());
            return new ArrayList<>();
        }
    }
    
    /**
     * 将国家资源数据转换为本地资源对象
     */
    private DataDirectResource convertToLocalResource(NationalResourceData nationalData) {
        if (nationalData == null) {
            return new DataDirectResource();
        }
        
        DataDirectResource localResource = new DataDirectResource();
        localResource.setResourceId(nationalData.getResourceId());
        localResource.setResourceName(nationalData.getResourceName());
        localResource.setResourceCode(nationalData.getResourceCode());
        localResource.setResourceType(nationalData.getResourceType());
        localResource.setResourceDesc(nationalData.getResourceDesc());
        localResource.setStatus(nationalData.getStatus());
        localResource.setDataSource(nationalData.getDataSource());
        localResource.setDataVersion(nationalData.getDataVersion());
        localResource.setIsValid(nationalData.getIsValid());
        localResource.setSyncTime(new Date());
        localResource.setRemark(nationalData.getRemark());
        
        return localResource;
    }
}
